package com.wk.paradise.redis.config.redisConfig;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolAbstract;
import redis.clients.jedis.Protocol;

/**
 * @Classname RedisPool
 * @Description TODO
 * @Date 2019/12/16 11:15
 * @Author by weikai
 */
@Component
public class RedisPool extends JedisPoolAbstract implements CommandLineRunner {

  private final Logger LOGGER = LoggerFactory.getLogger(RedisPool.class);

  @Value("${redis.host}")
  private String host;

  @Value("${redis.port}")
  private int port;

  @Value("${redis.password}")
  private String password;

  @Value("${redis.maxIdle}")
  private String maxIdle;

  @Value("${redis.maxActive}")
  private String maxActive;

  @Value("${redis.maxWait}")
  private String maxWait;


  private GenericObjectPoolConfig poolConfig;

  public RedisPool() {
  }

  /**
   * 判断是否配置了redis的服务和端口
   */
  private boolean isConfiged(final String host, final int port) {

    if (StringUtils.isBlank(host) || !(port > 0)) {
      return false;
    }
    if (StringUtils.equals("${redis.host}", host)) {
      return false;
    }
    return true;
  }

  public void initPool(PooledObjectFactory<Jedis> factory) {

    if (this.internalPool != null) {
      try {
        closeInternalPool();
      } catch (Exception e) {
        LOGGER.warn("关闭redis连接池失败", e);
      }
    }
    this.internalPool = new GenericObjectPool<Jedis>(factory, poolConfig);
  }

  /**
   * 获得资源
   */
  @Override
  public Jedis getResource() {
    Jedis jedis = super.getResource();
    jedis.setDataSource(this);
    return jedis;
  }

  /**
   * @return the host
   */
  public String getHost() {
    return host;
  }

  /**
   * @param host the host to set
   */
  public void setHost(String host) {
    this.host = host;
  }

  /**
   * @return the port
   */
  public int getPort() {
    return port;
  }

  /**
   * @param port the port to set
   */
  public void setPort(int port) {
    if (StringUtils.isEmpty(String.valueOf(this.port))) {
      this.port = -1;
    }
    this.port = port;
  }

  /**
   * @return the poolConfig
   */
  public GenericObjectPoolConfig getPoolConfig() {
    return poolConfig;
  }

  /**
   * @param poolConfig the poolConfig to set
   */
  public void setPoolConfig(GenericObjectPoolConfig poolConfig) {
    this.poolConfig = poolConfig;
  }


  @Override
  public void run(String... strings) throws Exception {
    RedisPoolConfig redisPoolConfig = new RedisPoolConfig();
    redisPoolConfig.setMaxIdleStr(maxIdle);
    redisPoolConfig.setMaxTotalStr(maxActive);
    redisPoolConfig.setMaxWaitMillisStr(maxWait);

    LOGGER.info("redisPoolConfig配置，maxIdle:{},maxActive:{},maxWait:{}",maxIdle,maxActive,maxWait);

    redisPoolConfig.run();
    poolConfig = redisPoolConfig;
    if (!isConfiged(host, port)) {
      return;
    }
    if (StringUtils.isBlank(password)) {
      LOGGER.info("无密码初始化redis，host:{},port:{}",host,port);
      initPool(new RedisFactory(host, port, Protocol.DEFAULT_TIMEOUT, null,
          Protocol.DEFAULT_DATABASE, null));
    } else {
      LOGGER.info("有密码初始化redis，host:{},port:{}",host,port);
      initPool(new RedisFactory(host, port, Protocol.DEFAULT_TIMEOUT, password,
          Protocol.DEFAULT_DATABASE, null));
    }
  }
}
